<template>
  <el-dialog 
    :title="title" 
    :visible.sync="open" 
    width="60%" 
    append-to-body 
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="true"
    @close="handleClose">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备名称" prop="deviceName">
                <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
              </el-form-item>
              <el-form-item label="所属产品" prop="productId" class="product-select">
                <el-input v-model="form.productName" placeholder="产品名称" readonly>
                  <el-button slot="append" @click="openProductSelect">选择</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="设备编号" prop="deviceCode">
                <el-input v-model="form.deviceCode" placeholder="请输入设备编号">
                  <el-button slot="append" @click="handleGenerateCode">生成</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="固件版本" prop="firmwareVersion">
                <el-input v-model="form.firmwareVersion" placeholder="请输入固件版本"/>
              </el-form-item>
              <el-form-item label="设备状态">
                <el-tag :type="getStatusType(form.status)">{{ getStatusText(form.status) }}</el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="定位方式" prop="locationWay">
                <el-select v-model="form.locationWay" placeholder="请选择定位方式">
                  <el-option label="自动定位" :value="1"/>
                  <el-option label="设备定位" :value="2"/>
                  <el-option label="自定义" :value="3"/>
                </el-select>
              </el-form-item>
              <el-form-item label="设备经度" prop="longitude" v-show="form.locationWay === 3">
                <el-input v-model="form.longitude" placeholder="请输入设备经度">
              <el-button slot="append" @click="handleGetLocation('longitude')">坐标拾取</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="设备纬度" prop="latitude" v-show="form.locationWay === 3">
                <el-input v-model="form.latitude" placeholder="请输入设备纬度">
              <el-button slot="append" @click="handleGetLocation('latitude')">坐标拾取</el-button>
                </el-input>
              </el-form-item>
              <el-form-item label="激活时间">
                <el-input v-model="form.activeTime" placeholder="设备激活时间" readonly>
                  <template slot="prepend">
                    <i class="el-icon-date"></i>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="信号强度">
                <el-input v-model="form.rssi" disabled/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="禁用设备" prop="disabled">
                <el-switch v-model="form.disabled"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注信息">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入备注信息"/>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
                  </div>

    <!-- 产品选择对话框 -->
    <el-dialog title="选择产品" :visible.sync="productDialogVisible" width="600px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="产品名称" align="center" prop="productName" />
        <el-table-column label="产品类型" align="center" prop="deviceType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_device_type" :value="scope.row.deviceType"/>
          </template>
        </el-table-column>
        <el-table-column label="传输协议" align="center" prop="transProtocol">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_trans_protocol" :value="scope.row.transProtocol"/>
          </template>
        </el-table-column>
        <el-table-column label="启动授权" align="center" prop="isAuthRequired">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.isAuthRequired"/>
          </template>
        </el-table-column>
        <el-table-column label="认证方式" align="center" prop="authMethod">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.iot_auth_method" :value="scope.row.authMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="产品编号" align="center" prop="id" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getProductList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmSelectProduct">确 定</el-button>
        <el-button @click="productDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 地图选择对话框 -->
    <el-dialog title="坐标拾取" :visible.sync="mapDialogVisible" width="800px" append-to-body>
      <div class="map-container">
        <!-- <baidu-map 
          ref="baiduMap"
          :longitude="mapCenter.lng"
          :latitude="mapCenter.lat"
          :zoom="mapZoom"
          :editable="true"
          style="height: 500px;"
          @marker-move="handleMarkerMove"
        /> -->
        <a-map
          ref="aMapGL"
          :longitude="mapCenter.lng"
          :latitude="mapCenter.lat"
          :zoom="mapZoom"
          :editable="true"
          style="height: 500px;"
          @marker-move="handleMarkerMove"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmLocation">确 定</el-button>
        <el-button @click="mapDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { getDevice, addDevice, updateDevice } from "@/api/iot/device";
import { listProduct } from "@/api/iot/product";
import { parseTime } from "@/utils/ruoyi";
import DictTag from "@/components/DictTag";
import Pagination from "@/components/Pagination";
import BaiduMap from "@/components/BaiduMap";
import AMap from "@/components/AMap";

export default {
  name: "DeviceForm",
  components: {
    DictTag,
    Pagination,
    BaiduMap,
    AMap
  },
  props: {
    deviceId: {
      type: [String, Number],
      default: null
    }
  },
  dicts: ['sys_yes_no', 'iot_device_type', 'iot_trans_protocol', 'iot_auth_method'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      // 是否显示弹出层
      open: false,
      // 弹出层标题
      title: "",
      // 产品选择对话框
      productDialogVisible: false,
      // 产品列表
      productList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        deviceType: undefined,
        transProtocol: undefined,
        isAuthRequired: undefined,
        authMethod: undefined,
        id: undefined
      },
      // 表单参数
      form: {
        id: undefined,
        deviceName: undefined,
        productId: undefined,
        productName: undefined,
        deviceCode: undefined,
        firmwareVersion: undefined,
        status: 1,
        rssi: undefined,
        locationWay: 1,
        thingModelValue: undefined,
        longitude: undefined,
        latitude: undefined,
        activeTime: undefined,
        deviceImage: undefined,
        disabled: false,
        remark: undefined
      },
      // 表单校验规则
      rules: {
        deviceName: [
          { required: true, message: "设备名称不能为空", trigger: "blur" }
        ],
        productId: [
          { required: true, message: "所属产品不能为空", trigger: "change" }
        ],
        deviceCode: [
          { required: true, message: "设备编号不能为空", trigger: "blur" }
        ]
      },
      // 地图选择对话框
      mapDialogVisible: false,
      // 地图中心点
      mapCenter: {
        lng: 116.404,
        lat: 39.915
      },
      // 地图缩放级别
      mapZoom: 15,
      // 当前选择的坐标
      selectedLocation: {
        lng: null,
        lat: null
      },
      // 搜索关键词
      searchKeyword: '',
      // 当前编辑的字段（经度/纬度）
      currentEditField: '',
      // 地图加载状态
      mapLoading: true
    };
  },
  watch: {
    deviceId: {
      handler(val) {
        if (val) {
          this.open = true;
          this.title = "修改设备";
          this.getInfo(val);
        } else if (val === 0) {
          this.reset();
          this.open = true;
          this.title = "添加设备";
        }
      }
    }
  },
  created() {
    // 初始化字典数据
    this.getDicts("sys_yes_no").then(response => {
      this.dict.type.sys_yes_no = response.data;
    });
    this.getDicts("iot_device_type").then(response => {
      this.dict.type.iot_device_type = response.data;
    });
    this.getDicts("iot_trans_protocol").then(response => {
      this.dict.type.iot_trans_protocol = response.data;
    });
    this.getDicts("iot_auth_method").then(response => {
      this.dict.type.iot_auth_method = response.data;
    });
  },
  methods: {
    /** 查询产品列表 */
    getProductList() {
      this.loading = true;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 打开产品选择对话框 */
    openProductSelect() {
      this.productDialogVisible = true;
      this.getProductList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getProductList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        deviceType: undefined,
        transProtocol: undefined,
        isAuthRequired: undefined,
        authMethod: undefined,
        id: undefined
      };
      this.handleQuery();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        deviceName: undefined,
        productId: undefined,
        productName: undefined,
        deviceCode: undefined,
        firmwareVersion: undefined,
        status: 1,
        rssi: undefined,
        locationWay: 1,
        thingModelValue: undefined,
        longitude: undefined,
        latitude: undefined,
        activeTime: undefined,
        deviceImage: undefined,
        disabled: false,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
    },
    /** 确认选择产品 */
    confirmSelectProduct() {
      if (this.ids.length !== 1) {
        this.$modal.msgError("请选择一个产品");
        return;
      }
      const product = this.productList.find(item => item.id === this.ids[0]);
      this.form.productId = product.id;
      this.form.productName = product.productName;
      this.productDialogVisible = false;
    },
    /** 获取设备详细信息 */
    getInfo(deviceId) {
      getDevice(deviceId).then(response => {
        if (response.data) {
          this.form = response.data;
        }
      });
    },
    /** 生成设备编号 */
    handleGenerateCode() {
      // TODO: 实现设备编号生成逻辑
    },

    /** 打开地图选择 */
    handleGetLocation(field) {
      this.currentEditField = field;
      this.mapDialogVisible = true;
      this.mapLoading = true;
      
      // 如果已有经纬度，则设置地图中心点和标记
      if (this.form.longitude && this.form.latitude) {
        const lng = parseFloat(this.form.longitude);
        const lat = parseFloat(this.form.latitude);
        
        if (!isNaN(lng) && !isNaN(lat) && 
            lng >= -180 && lng <= 180 && 
            lat >= -90 && lat <= 90) {
          this.mapCenter = {
            lng: lng,
            lat: lat
          };
          this.selectedLocation = { ...this.mapCenter };
        }
      }
      
      this.$nextTick(() => {
        this.mapLoading = false;
      });
    },

    /** 处理地图搜索 */
    handleSearch() {
      if (this.searchKeyword && this.$refs.baiduMap) {
        this.$refs.baiduMap.geocodeAddress(this.searchKeyword);
      }
    },

    /** 地图标记点移动事件 */
    handleMarkerMove(position) {
      console.log('标记点移动:', position);
      if (position && position.longitude && position.latitude) {
        this.selectedLocation = {
          lng: position.longitude,
          lat: position.latitude
        };
      }
    },

    /** 确认选择坐标 */
    confirmLocation() {
      if (!this.selectedLocation.lng || !this.selectedLocation.lat) {
        this.$modal.msgError("请先在地图上选择位置");
        return;
      }
      
      // 保留6位小数
      this.form.longitude = this.selectedLocation.lng.toFixed(6);
      this.form.latitude = this.selectedLocation.lat.toFixed(6);
      this.mapDialogVisible = false;
    },
    /** 获取状态显示文本 */
    getStatusText(status) {
      const statusMap = {
        1: '未激活',
        2: '禁用',
        3: '在线',
        4: '离线'
      };
      return statusMap[status] || '未知';
    },
    /** 获取状态显示类型 */
    getStatusType(status) {
      const typeMap = {
        1: 'info',
        2: 'danger',
        3: 'success',
        4: 'warning'
      };
      return typeMap[status] || '';
    },
    /** 提交表单 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateDevice(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("success");
              this.open = false;
              this.$emit('update:deviceId', null);
            });
          } else {
            addDevice(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("success");
              this.open = false;
              this.$emit('update:deviceId', null);
            });
          }
        }
      });
    },
    /** 处理对话框关闭 */
    handleClose() {
      this.$emit('update:deviceId', null);
    }
  }
};
</script>

<style scoped>
.el-tag {
  margin-right: 10px;
}

.el-input-number {
  width: 100%;
}

/* 产品选择样式 */
.product-select :deep(.el-input-group__append) {
  background-color: var(--el-color-primary);
  border-color: var(--el-color-primary);
  color: white;
  cursor: pointer;
}

.product-select :deep(.el-input-group__append:hover) {
  background-color: var(--el-color-primary-light-3);
  border-color: var(--el-color-primary-light-3);
}

.map-container {
  width: 100%;
  height: 500px;
  position: relative;
  margin-bottom: 20px;
}

/* 隐藏百度地图Logo和版权信息 */
:deep(.anchorBL) {
  display: none !important;
}

/* 隐藏左上角的按钮组 */
:deep(.BMap_stdMpCtrl) {
  display: none !important;
}

/* 隐藏右下角的缩放控件 */
:deep(.BMap_omCtrl) {
  display: none !important;
}
</style> 